require 'webrick'
include WEBrick

# === comet 用サーブレット
#
# Author:: krdlab
#
class NightSkyServlet < HTTPServlet::AbstractServlet

  # サーバとの連携

  def wait_message
    @server.add_to_waiters(Thread.current)
    Thread.stop
  end

  def release_waiting
    @server.remove_from_waiters(Thread.current)
  end

  def closing?
    Thread.current[:CloseServerRequired]
  end

  def wakeup_waiters
    @server.wakeup_waiters
  end

  # common

  def get_json(req)
    req.query['json']
  end

  # GET

  def do_GET(req, res)
    if req.query['type'] == 'wait' then
      do_main(req, res)
    else
      connect_first(req, res)
    end
  end

  def do_main(req, res)
    begin
      wait_message
      if closing? then
        do_closing(req, res)
      else
        response_to_waiters(req, res)
      end
    ensure
      release_waiting
    end
  end

  def do_closing(req, res)
    # closing server...
  end

  def response_to_waiters(req, res)
  end

  def connect_first(req, res)
  end

  # POST

  def do_POST(req, res)
    response_to_posted_client(req, res)
    wakeup_waiters
  end

  def response_to_posted_client(req, res)
  end
end

